package com.example.mygame.snake.widget;

import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.View;

import androidx.appcompat.app.AlertDialog;

import com.example.mygame.snake.common.Direction;
import com.example.mygame.snake.common.GameConst;
import com.example.mygame.snake.role.Food;
import com.example.mygame.snake.role.Map;
import com.example.mygame.snake.role.MapBlock;
import com.example.mygame.snake.role.Snake;

import java.util.Random;

/**
 * Created by Mrper on 15-11-24.
 */
public class GameView extends View {

    private Paint paint;
    private Map map;
    private Snake snake;
    private Food food;
    private Random random = new Random();

    private static final int MSG_REFRESH_SNAKE = 0x0001;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case MSG_REFRESH_SNAKE:
                    snake.autoMove();
                    invalidate();
                    break;
                default:
                    break;
            }
        }
    };

    public GameView(Context context) {
        super(context);
        initGameView();
    }

    public GameView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initGameView();
    }

    public GameView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initGameView();
    }

    private void initGameView(){
        paint = new Paint();
        map = new Map();
        snake = new Snake();
        food = new Food();
        snake.setOnSnakeMoveListener(new Snake.OnSnakeMoveListener() {
            @Override
            public void onMove() {
                handler.sendEmptyMessage(MSG_REFRESH_SNAKE);
            }

            @Override
            public void onPreviewNextHeader(MapBlock headerBlock) {
                if(food.point!=null && food.point.x == headerBlock.x && food.point.y == headerBlock.y) {
                    snake.body.add(0,new MapBlock(food.point.x,food.point.y));
                    food.createFood(snake);//重新创建食物
                    invalidate();//刷新界面
                }else{
                    if(snake.isGameOver(headerBlock)) {
                        showGameOverDialog();//显示游戏结束的提示框
                        return;
                    }
                }

            }

        });
        food.setOnCreateFoodListener(new Food.OnCreateFoodListener() {
            @Override
            public void onFinishCreateFood(MapBlock food) {
                invalidate();
            }
        });
        snake.isAutoMove = true;
        snake.start();
        food.createFood(snake);
    }

    /**
     * 显示游戏结束的提示框
     */
    public void showGameOverDialog(){
        new AlertDialog.Builder(getContext())
                .setMessage("Game Over!")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        snake.resetSnake();//重置贪吃蛇
                        food.createFood(snake);//创建食物
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                snake.run();
                            }
                        }).start();
                    }
                }).show();
    }

    /**
     * 手动设置贪吃蛇的运行方向
     * @param direction
     */
    public void goDirection(Direction direction){
        if(snake.isAlive) {
            snake.isAutoMove = false;
            snake.goDirection(direction);
            snake.isAutoMove = true;
            invalidate();//刷新界面
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawColor(Color.WHITE);

        int width = getMeasuredWidth(), height = getMeasuredHeight();
        System.out.println(String.format("=====> snake map: w = %d, h = %d", width, height));

        //画笔设置
        paint.reset();
        paint.setAntiAlias(true);
        paint.setColor(Color.BLACK);

        //绘制地图
        for (int y = 0; y < map.map.length; y++) {
            for (int x = 0; x < map.map[0].length; x++) {
                canvas.drawRect(new Rect(x + 1 + GameConst.BLOCK_SIZE * x, y + 1 + GameConst.BLOCK_SIZE * y,
                        x + 1 + GameConst.BLOCK_SIZE * (x + 1), y + 1 + GameConst.BLOCK_SIZE * (y + 1)), paint);
            }
        }

        paint.setColor(Color.LTGRAY);
        //绘制贪吃蛇
        for (int i = 0; i < snake.body.size(); i++) {
            MapBlock value = snake.body.get(i);
            canvas.drawRect(new Rect(value.x + 1 + GameConst.BLOCK_SIZE * value.x, value.y + 1 + GameConst.BLOCK_SIZE * value.y,
                    value.x + 1 + GameConst.BLOCK_SIZE * (value.x + 1), value.y + 1 + GameConst.BLOCK_SIZE * (value.y + 1)), paint);
        }

        paint.setColor(Color.rgb(random.nextInt(256), random.nextInt(256), random.nextInt(256)));//随机颜色，闪动
        //绘制食物
        if (food.point != null) {
            canvas.drawRect(new Rect(food.point.x + 1 + GameConst.BLOCK_SIZE * food.point.x, food.point.y + 1 + GameConst.BLOCK_SIZE * food.point.y,
                    food.point.x + 1 + GameConst.BLOCK_SIZE * (food.point.x + 1), food.point.y + 1 + GameConst.BLOCK_SIZE * (food.point.y + 1)), paint);
        }
    }

}
